let express = require('express');
let router = express.Router();
let profileDao = require('../../model/admin/profile.js')
let unility = require('../../common/unility')

//渲染个人信息界面
router.get('/', async function (req, res) {

    let userId = req.session.user.userId;
    let profileDetail = await profileDao.getUserDetail(userId);
    delete profileDetail.password;
    await res.render('person/person', {
        profileDetail
    });
})

//个人基本信息修改

router.post('/basic', async function (req, res) {
    let userId = req.session.user.userId;
    let userName = req.body.userName;
    let phone = req.body.phone;
    let email = req.body.email;
    if (!phone) {
        return await res.json({
            status: 203,
            msg: "请输入手机号！"
        })
    }
    if (!email) {
        return await res.json({
            status: 203,
            msg: "请输入邮箱地址！"
        })
    }
    if (!userName) {
        return await res.json({
            status: 203,
            msg: "请输入您的用户名昵称！"
        })
    }
    //验证用户名昵称是否重复
    let valicationUserName = await profileDao.valicationUserName(userId, userName);
    if (valicationUserName.length > 0) {
        return await res.json({
            status: 203,
            msg: "昵称重复，请重新输入用户名昵称！"
        })
    }
    //更改用户基本信息
    await profileDao.updateUserBasic(userId, userName, phone, email);
    await res.json({
        status: 200,
        msg: "success"
    });

})
//用户头像修改
router.post('/avatar', async function (req, res) {
    let avatar = req.body.imgUrl;
    let userId = req.session.user.userId;
    if (!avatar) {
        return await res.json({
            status: 203,
            msg: "请上传头像！"
        })
    }
    //执行头像修改动作
    await profileDao.updateUserAvatar(userId, avatar);
    await res.json({
        status: 200,
        msg: "success"
    });


})

//用户密码修改
router.post("/pwd/update", async function (req, res) {
    let userId = req.session.user.userId;
    let nowpass = req.body.nowpass;
    let pass = req.body.pass;
    //验证原密码输入是否正确
    let profileDetail = await profileDao.getUserDetail(userId);
    let nowpassMd5 = await unility.encryptPWD(nowpass);
    if(nowpassMd5 != profileDetail.password){
        return res.json({
            status: 203,
            msg: "当前密码输入错误，请重新输入！"
        })  
    }
    //验证俩次密码输入是否一致
    if (nowpass === pass) {
        return res.json({
            status: 203,
            msg: "新密码与原密码一致，请重新输入新密码！"
        })
    }
   //加密新密码
   let newPass  = await unility.encryptPWD(pass);
   await profileDao.updatePwd(userId,newPass);
   delete req.session.user;
   await res.json({status:200,msg:"success"})
})


module.exports = router;